package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.dao.TbOrderRepository;
import com.qf.pojo.BaseResult;
import com.qf.pojo.TbOrder;
import com.qf.pojo.TbShopVo;
import com.qf.service.AlipayService;
import com.qf.utils.AlipayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by 54110 on 2021/5/12.
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TbOrderRepository tbOrderRepository;

    @Override
    public String pay(List ids,String userid) {
        //获取到要支付的商品结合
        Boolean aBoolean = redisTemplate.hasKey("shopcart_" + userid);
        //声明总的钱数
        Double price = 0.0;
        //声明订单id
        String uuid = UUID.randomUUID().toString();
        if (aBoolean&&ids.size()>0){
            //从 redis hash获取到商品集合
            for (int i=0;i<ids.size();i++
                 ) {
                Object o = redisTemplate.opsForHash().get("shopcart_" + userid, ids.get(i).toString());
                //将从redis中获取到 object转为对象
                String string = JSONObject.toJSONString(o);
                TbShopVo tbShopVo = JSONObject.parseObject(string, TbShopVo.class);
                //获取到当前商品的钱数
                price+=tbShopVo.getPrice()*tbShopVo.getNum();
                //获取 完成后 就可以删除当前的购物车内容
                redisTemplate.opsForHash().delete("shopcart_"+userid,ids.get(i).toString());
            }


            //声明订单对象
            TbOrder tbOrder = new TbOrder();
            tbOrder.setCreateTime(new Date());
            tbOrder.setOrderid(uuid);
            tbOrder.setPrice(price);
            tbOrder.setStatus("WATI_PAY");
            //存储未支付的订单信息后，请求支付宝，获取到支付链接
            tbOrderRepository.save(tbOrder);
            //请求支付宝支付
            AlipayUtils alipayUtils = new AlipayUtils();
            Map map = new HashMap<>();
            map.put("orderid",uuid);
            map.put("totalPrice",price);
            String pay = alipayUtils.pay(map);
           return pay;

        }
        return "ok";
    }

    @Override
    public void updateStatus(String out_trade_no, String trade_status) {
        TbOrder byOrderid = tbOrderRepository.findByOrderid(out_trade_no);
        //改变状态
        byOrderid.setStatus(trade_status);
        byOrderid.setPayTime(new Date());
        tbOrderRepository.saveAndFlush(byOrderid);
    }
}
